package net.bbtang.website.controller;



import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bbtang.website.pojo.OrderInfoDTO;
import net.bbtang.website.service.OrderInfoService;
import net.bbtang.website.service.UserInfoService;
import net.bbtang.website.utils.ConstantsStatus;
import net.bbtang.website.utils.OrderConstantsStatus;
import net.bbtang.website.utils.StatusCode;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/orderInfo")
public class OrderInfoApiController {
	@Autowired
	OrderInfoService orderInfoService;
	@Autowired
	UserInfoService userInfoService;
	
	private static final Logger logger = Logger.getLogger(OrderInfoApiController.class); 
	
	/**初始增加订单
	 @api {post} /orderInfo/initOrder 初始增加订单接口
	 
	 @apiParam {int} publishId 发布id 必填
	 @apiParam {int} publishType 发布类型（订单发布类型：悬赏1，分享2，小组3） 必填
	 @apiParam {int} userId 用户id 必填

	 @apiSuccess {boolean} flag 请求状态，码状态   成功：true 失败：false
	 @apiSuccess {String} num 状态码值
	 @apiSuccess {String} detailMsg 状态码详细值
	 @apiSuccess {Object} data 返回数据
	
	 @apiParamExample {json} 请求参数Demo:
	 {
		"userId":1,
	}

	@apiSuccessExample {json} 请求成功结果Demo:
	{
	    "number": "2000",
	    "flag": true
	}

	@apiErrorExample {json} 请求成功得异常结果
	HTTP/1.1 5000 error
	{
	  "number": "5000",
	  "flag": false,
	  "detailMsg": "初始增加订单异常"
	}

	@apiErrorExample  请求参数异常
		HTTP/1.1 400
	@apiErrorExample  请求数据类型异常
	HTTP/1.1 415
	@author wxw
	 */
	@RequestMapping(value = "/initOrder", method = RequestMethod.POST)
	@ResponseBody
	public Object initOrder(@RequestBody Object body,HttpServletRequest request,HttpServletResponse response) {
		StatusCode<Object> sc=new StatusCode<Object>(ConstantsStatus.SC2000);
		
		try {
			JSONObject jb = JSONObject.fromObject(body);
			if(!jb.containsKey("publishId")){
				throw new Exception("publishId is null");
			}
			if(!jb.containsKey("publishType")){
				throw new Exception("publishType is null");
			}
			if(!jb.containsKey("userId")){
				throw new Exception("userId is null");
			}
//			if(!jb.containsKey("orderType")){
//				throw new Exception("orderType is null");
//			}
			OrderInfoDTO orderInfoDTO = (OrderInfoDTO)JSONObject.toBean(jb, OrderInfoDTO.class);
			orderInfoDTO.setOrderStatus(OrderConstantsStatus.ORDER_HOLD);
			orderInfoService.initOrder(orderInfoDTO);
			sc.setFlag(true);
			
		} catch (Exception e) {
			e.printStackTrace();
			sc.codes(ConstantsStatus.SC5000);
			sc.setDetailMsg("初始增加订单异常");
		}
		
		return sc;
	
	}
	
	/**更新订单状态
	 @api {post} /orderInfo/updateOrderType 更新订单状态
	 
	 @apiParam {int} orderId 订单id 必填
	 @apiParam {int} orderStatus 订单状态：-1：取消  1：已抢单  2：已完成 3：已投诉 必填
	 @apiParam {int} complaintUserId 投诉者id 非必填（orderStatus=3有此字段）
	 @apiParam {int} complaintContent  投诉内容  非必填（orderStatus=3有此字段）

	 @apiSuccess {boolean} flag 请求状态，码状态   成功：true 失败：false
	 @apiSuccess {String} num 状态码值
	 @apiSuccess {String} detailMsg 状态码详细值
	 @apiSuccess {Object} data 返回数据
	
	 @apiParamExample {json} 请求参数Demo:
	 {
		"orderId":1,
		"orderStatus":2,
	}

	@apiSuccessExample {json} 请求成功结果Demo:
	{
	  "number": "2000",
	  "flag": true,
	  "data": {
	    "id": 3,个人积分标识
	    "userId": 111,用户id
	    "score": 100,总积分
	    "useState": 0,用户积分状态 0：正常 1：停用
	    "createTime": 1492093771000,创建时间
	    "updateTime": 1492093774000    更新时间
	  }
	}

	@apiErrorExample {json} 请求成功得异常结果
	HTTP/1.1 5000 error
	{
	  "number": "5000",
	  "flag": false,
	  "detailMsg": "状态更新异常"
	}

	@apiErrorExample  请求参数异常
		HTTP/1.1 400
	@apiErrorExample  请求数据类型异常
	HTTP/1.1 415
	@author wxw
	 */
	@RequestMapping(value = "/updateOrderType", method = RequestMethod.POST)
	@ResponseBody
	public Object updateOrderType(@RequestBody Object body,HttpServletRequest request,HttpServletResponse response) {
		StatusCode<Object> sc=new StatusCode<Object>(ConstantsStatus.SC2000);
		
		try {
			JSONObject jb = JSONObject.fromObject(body);
			Integer orderStatus = null;
			Integer orderId = null;
//			Integer confirmType = null;
			
			if(!jb.containsKey("orderId")){
				throw new Exception("orderId is null");
			}else{
				orderId = jb.getInt("orderId");
			}
			OrderInfoDTO searchStatus = new OrderInfoDTO();
			searchStatus.setOrderId(orderId);
			OrderInfoDTO order = orderInfoService.getOrderInfoList(searchStatus).get(0);
			
//			if(jb.containsKey("confirmType")){//1:手动确认  2：扫码确认
//				confirmType = jb.getInt("confirmType");
//			}
			
			
			if(!jb.containsKey("orderStatus")){
				throw new Exception("orderStatue is null");
			}else{
				orderStatus = jb.getInt("orderStatus");
			}
		
			
			if(orderStatus.equals(OrderConstantsStatus.ORDER_CALCEL)){
				//抢单状态禁止取消
				if(!order.getOrderStatus().equals(OrderConstantsStatus.ORDER_HOLD)){
					sc.codes(ConstantsStatus.SC5000);
					sc.setDetailMsg("非待抢单状态下禁止取消");
					return sc;
				}
			}
			
			if(orderStatus.equals(OrderConstantsStatus.ORDER_HOLD_CONFIRM)){
				if(!jb.containsKey("payOrder")){
					sc.codes(ConstantsStatus.SC5000);
					sc.setDetailMsg("未上传支付凭证");
					return sc;
				}
			}
			
			if(orderStatus.equals(OrderConstantsStatus.ORDER_COMPLAINT)){
				if(!jb.containsKey("complaintUserId")){
					sc.codes(ConstantsStatus.SC5000);
					sc.setDetailMsg("complaintUserId is null");
					return sc;
				}
				if(!jb.containsKey("complaintContent")){
					sc.codes(ConstantsStatus.SC5000);
					sc.setDetailMsg("complaintContent is null");
					return sc;
				}
			}
			OrderInfoDTO orderInfoDTO = (OrderInfoDTO)JSONObject.toBean(jb, OrderInfoDTO.class);
//			orderInfoDTO.setOrderStatus(OrderConstantsStatus.ORDER_HOLD);
			orderInfoService.updateOrderType(orderInfoDTO);
			sc.setFlag(true);
			
		} catch (Exception e) {
			e.printStackTrace();
			sc.codes(ConstantsStatus.SC5000);
			sc.setDetailMsg("状态更新异常");
		}
		
		return sc;
	
	}
	
	
	
	/**获取订单列表
	 @api {post} /orderInfo/getOrderInfoList 获取订单列表
	 
	 @apiParam {int} userId 用户id 必填

	 @apiSuccess {boolean} flag 请求状态，码状态   成功：true 失败：false
	 @apiSuccess {String} num 状态码值
	 @apiSuccess {String} detailMsg 状态码详细值
	 @apiSuccess {Object} data 返回数据
	
	 @apiParamExample {json} 请求参数Demo:
	 {
		"userId":1,
	}

	@apiSuccessExample {json} 请求成功结果Demo:
	{
	    "number": "2000",
	    "flag": false,
	    "data":
	    [
	        {
	            "publishId": 1,  发布id
	            "publishType": 1,  发布类型 ，悬赏：0，分享：1
	            "acceptUserId": 2,  接受订单用户id
	            "userId": 1,  发布订单用户id
	            "orderStatus": 2, 订单状态：-1：取消  1：已抢单  2：已完成 3：已投诉 
	            "complaintUserId": 1,  投诉者id
	            "complaintContent": "哈哈哈",  投诉内容
	            "complaintTime": 1492433973000,  投诉时间
	            "payOrder": "www.baidu.com",  支付凭证图片地址
	            "createTime": 1492433936000,  创建时间
	            "updateTime": 1492433939000,  更新时间
	            "userInfo":    发布者用户信息
	            {
	                "id": 1,
	                "userName": "张小盒",
	                "sex": 0,
	                "headImage": "www.baidu.com",
	                "studentCardMain": "www.baidu.com",
	                "studentCardBack": "www.baidu.com",
	                "telphone": "15022222222",
	                "dormitoryNo": "1-2-301",
	                "wechatNo": "12345",
	                "qqNo": "54321",
	                "personalSignature": "好孩子",
	                "universityId": 1,
	                "changeUniversityNum": 0,
	                "isRealName": 1,
	                "isGroup": 1,
	                "qrcode": "www",
	                "openId": "qweqweqweqwe",
	                "createTime": 1492176561000,
	                "updateTime": 1492176564000
	            },
	            "accessUserInfo":  接受者用户信息
	            {
	                "id": 2,
	                "userName": "侯亮平",
	                "sex": 1,
	                "headImage": "www.baidu.com",
	                "studentCardMain": "www.baidu.com",
	                "studentCardBack": "www.baidu.com",
	                "telphone": "1956756757",
	                "dormitoryNo": "2-2-222",
	                "wechatNo": "555",
	                "qqNo": "555",
	                "personalSignature": "555",
	                "universityId": 1,
	                "changeUniversityNum": 0,
	                "isRealName": 1,
	                "isGroup": 1,
	                "qrcode": "232",
	                "openId": "3123124asda",
	                "createTime": 1492176980000,
	                "updateTime": 1492176983000
	            },
	            "publishInfo":  发布订单信息
	            {
	                "id": 1,
	                "userId": 1,
	                "publishType": 0,
	                "publishPayType": 0,
	                "publishPrice": "10",
	                "publishState": 3,
	                "createtime": 1492237413000,
	                "updatetime": 1492238235000,
	                "info": "帮我带一份拉面",
	                "address": "一公寓401",
	                "contactInformation": "15022222222",
	                "contactName": "赵日天",
	                "userGroupId": -1,
	                "orderStatus": 2
	            }
	        },
	        {
	            "publishId": 2,
	            "publishType": 1,
	            "acceptUserId": 2,
	            "userId": 1,
	            "orderStatus": 2,
	            "confirmType": 2,
	            "complaintUserId": 5,
	            "complaintContent": "呵呵呵",
	            "complaintTime": 1492434043000,
	            "createTime": 1492434028000,
	            "updateTime": 1492434031000,
	            "userInfo":
	            {
	                "id": 1,
	                "userName": "张小盒",
	                "sex": 0,
	                "headImage": "www.baidu.com",
	                "studentCardMain": "www.baidu.com",
	                "studentCardBack": "www.baidu.com",
	                "telphone": "15022222222",
	                "dormitoryNo": "1-2-301",
	                "wechatNo": "12345",
	                "qqNo": "54321",
	                "personalSignature": "好孩子",
	                "universityId": 1,
	                "changeUniversityNum": 0,
	                "isRealName": 1,
	                "isGroup": 1,
	                "qrcode": "www",
	                "openId": "qweqweqweqwe",
	                "createTime": 1492176561000,
	                "updateTime": 1492176564000
	            },
	            "accessUserInfo":
	            {
	                "id": 2,
	                "userName": "侯亮平",
	                "sex": 1,
	                "headImage": "www.baidu.com",
	                "studentCardMain": "www.baidu.com",
	                "studentCardBack": "www.baidu.com",
	                "telphone": "1956756757",
	                "dormitoryNo": "2-2-222",
	                "wechatNo": "555",
	                "qqNo": "555",
	                "personalSignature": "555",
	                "universityId": 1,
	                "changeUniversityNum": 0,
	                "isRealName": 1,
	                "isGroup": 1,
	                "qrcode": "232",
	                "openId": "3123124asda",
	                "createTime": 1492176980000,
	                "updateTime": 1492176983000
	            }
	        }
	    ]
	}

	@apiErrorExample {json} 请求成功得异常结果
	HTTP/1.1 5000 error
	{
	  "number": "5000",
	  "flag": false,
	  "detailMsg": "获取账户积分信息异常"
	}

	@apiErrorExample  请求参数异常
		HTTP/1.1 400
	@apiErrorExample  请求数据类型异常
	HTTP/1.1 415
	@author wxw
	 */
	@RequestMapping(value = "/getOrderInfoList", method = RequestMethod.POST)
	@ResponseBody
	public Object getOrderInfoList(@RequestBody Object body,HttpServletRequest request,HttpServletResponse response) {
		StatusCode<Object> sc=new StatusCode<Object>(ConstantsStatus.SC2000);
		try {
			JSONObject jb = JSONObject.fromObject(body);
			
			
			OrderInfoDTO orderInfo = new OrderInfoDTO();
			if(jb.containsKey("accessUserId")){
				Integer acceptUserId = jb.getInt("accessUserId");
				orderInfo.setAcceptUserId(acceptUserId);
			}
			
			if(jb.containsKey("publishType")){
				Integer publishType  = jb.getInt("publishType");//1:悬赏 2：分享 3：小组
				orderInfo.setPublishType(publishType);
			}
			if(jb.containsKey("userId")){
				Integer userId = jb.getInt("userId");
				orderInfo.setUserId(userId);
			}
			if(jb.containsKey("orderStatus")){
				/*
				  订单类型：
					-1：取消 
					0：待抢单 (小组订单预定后订单表插入一条，状态为待抢单，普通发单后状态为待抢单)
					1：已抢单 
					2：待确认完成
					3：已完成
					4：已投诉
				 */
				Integer orderStatus = jb.getInt("orderStatus");
				orderInfo.setOrderStatus(orderStatus);
			}
			List<OrderInfoDTO> orderList = orderInfoService.getOrderInfoList(orderInfo);
			sc.setData(orderList);
			
		} catch (Exception e) {
			e.printStackTrace();
			sc.codes(ConstantsStatus.SC5000);
			sc.setDetailMsg("获取订单列表异常");
		}
		
		
		return sc;
	
	}
	
	
}
